package com.million.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.million.commonutils.R;
import com.million.servicebase.exception.GuliException;
import com.million.vod.service.VodService;
import com.million.vod.utils.ConstantVodUtils;
import com.million.vod.utils.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.invoke.ConstantCallSite;
import java.util.List;

/**
 * @Author: studyboy
 * @Date: 2022/3/29  15:19
 */
@RestController
@RequestMapping("/eduvod/upVod")
public class VodController {

    @Autowired
    private VodService vodService;

    //上传视频
    @PostMapping("uploadVideo")
    public R uploadVideo(MultipartFile file){
        //返回视频id
       String videoId = vodService.uploadVideo(file);
       return R.ok().data("videoId",videoId);
    }

    //根据视频id 删除视频
    @DeleteMapping("deleteVod/{id}")
    public R deleteVod(@PathVariable("id") String id){
        vodService.deleteVod(id);
        return R.ok();
    }

    //根据课程id 删除该课程下的所有视频，用List  来封装，方便删除
    @DeleteMapping("removeAllVod")
    public R removeAllVod(@RequestParam("videoList")List<String> videoList) {
        vodService.removeAllVod(videoList);
        return R.ok();
    }

    //根据视频id获取视频的凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable("id") String id){
        //获取阿里云存储相关常量
        String accessKeyId = ConstantVodUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantVodUtils.ACCESS_KEY_SECRET;
        //ConstantCallSite
        DefaultAcsClient client = null;
        try {
            client = InitVodClient.initVodClient(accessKeyId,
                    accessKeySecret);
            //请求
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(id);
            //响应
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            //得到播放凭证
            String playAuth = response.getPlayAuth();
            //返回结果
            return R.ok().message("获取凭证成功").data("playAuth", playAuth);
        } catch (ClientException e) {
            throw new GuliException(20001,"播放视频失败");
        }
    }
}
